<?php
namespace app\admin\model;
use think\Model;
use think\Log;
class Goods extends Model
{

    function add($data)
    {
        $result = $this->isUpdate(false)->allowField(true)->save($data);
        if ($result) {
            return true;
        } else {
            return false;
        }
    }
    function edit($data)
    {
        $result = $this->isUpdate(true)->allowField(true)->save($data);
        if ($result) {
            return true;
        } else {
            return false;
        }
    }
    function batches($act, $params)
    {
        if ($act == 'delete') {
            $result = $this->destroy($params);
        }
        if ($result) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * 删除数据--单个
     * @param $id
     * @return int
     */
    public static function del($id)
    {
        try{
            $id = self::where('id',$id)->delete();
        } catch (Exception $exception) {
            return 0;
        }
        return $id;
    }

    /**
     * 批量处理淘宝搜索产品数据保存到本地库
     * @param $list_item
     * @return bool
     * @throws \Exception
     */
    public function saveGoodsItem($list_item)
    {
        if(!$list_item){
            return ['start_code'=>false];
        }

        $data_true = array();
        foreach ($list_item as $itemKey => $itemVal) {

            // 产品的折扣价要大于 1 元的
            if ($itemVal['couponPrice'] >= 1) {
                // 查找当前产品numIid本地是否存在
                $goods_id = $this->isTrueGoods($itemVal['numIid']);
                // 不存在则保存到本地
                if (empty($goods_id)) {
                    array_push($data_true, $itemVal);
                }
            }
        }

        if (!empty($data_true)) {
            try {
                $this->insertAll($data_true);
                Log::write('批量添加淘宝搜索商品成功！', 'info');
                return ['start_code'=>true,'num'=>count($data_true)];
            } catch (ErrorException $e) {
                Log::write('批量添加淘宝搜索商品失败！错误信息：' . $e->getMessage(), 'error');
            }
        }
    }

    /**
     * 根据产品numIID检测此商品是否存在
     * @param $numIID   产品numIID
     * @return bool
     */
    public function isTrueGoods($numIID){
        try{
            $isId = $this->where('numIid',$numIID)->value('id');
            if($isId){
                return true;
            }else{
                return false;
            }
        }catch(ErrorException $e){
            Log::write('检测产品是否存在异常产品产品numIID:'.$numIID.'、错误信息：'.$e->getMessage(), 'error');
        }
    }
}